package com.atguigu.gmall.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;

/**
 * @Author lzc
 * @Date 2022/4/29 11:32
 */
public class DWD_01_DwdTrafficBaseApp extends BaseAppV1 {
    public static void main(String[] args) {
        new DWD_01_DwdTrafficBaseApp()
            .init("DwdTrafficBaseApp", 3001, 1, "DwdTrafficBaseApp", "DwdTrafficBaseApp", "ods_log");
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 数据清洗: 非json格式的数据清洗掉
        SingleOutputStreamOperator<String> etledStream = etl(stream);
        // 2. 新老访客标记修复
        SingleOutputStreamOperator<JSONObject> validatedStream = validateOldOrNew(etledStream);
        // 3. 分流
        HashMap<String, DataStream<String>> topicToStreamMap = splitStream(validatedStream);
        // 4. 不同的流写入到不同的topic
        writeToKafka(topicToStreamMap);
    }
    
    private void writeToKafka(HashMap<String, DataStream<String>> topicToStreamMap) {
        topicToStreamMap.get("start").addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        topicToStreamMap.get("display").addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        topicToStreamMap.get("action").addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        topicToStreamMap.get("page").addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        topicToStreamMap.get("err").addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
    }
    
    private HashMap<String, DataStream<String>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {
        OutputTag<String> startTag = new OutputTag<String>("start") {};
        OutputTag<String> displayTag = new OutputTag<String>("display") {};
        OutputTag<String> actionTag = new OutputTag<String>("action") {};
        OutputTag<String> errTag = new OutputTag<String>("err") {};
        
        SingleOutputStreamOperator<String> pageStream = validatedStream.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject obj,
                                       Context ctx,
                                       Collector<String> collector) throws Exception {
                
                // 1. 错误日记: 任何一种日志有可能包含错误日志
                JSONObject err = obj.getJSONObject("err");
                if (err != null) {
                    ctx.output(errTag, obj.toJSONString());
                    
                    // 从jsonObject中删除错误信息
                    obj.remove("err");
                }
                
                // 2. 启动日志
                JSONObject start = obj.getJSONObject("start");
                if (start != null) {  // 启动日志
                    ctx.output(startTag, obj.toJSONString());
                } else {
                    JSONObject page = obj.getJSONObject("page");
                    JSONObject common = obj.getJSONObject("common");
                    Long ts = obj.getLong("ts");
                    
                    
                    JSONArray displays = obj.getJSONArray("displays");
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            display.putAll(page);
                            display.putAll(common);
                            display.put("ts", ts);
                            
                            ctx.output(displayTag, display.toJSONString());
                        }
                        obj.remove("displays");
                    }
                    
                    JSONArray actions = obj.getJSONArray("actions");
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);
                            action.putAll(common);
                            action.putAll(page);
                            action.put("ts", ts);
                            
                            ctx.output(actionTag, action.toJSONString());
                        }
                        obj.remove("actions");
                    }
                    
                    
                    // 一定是页面日志
                    collector.collect(obj.toJSONString());
                }
                
                
            }
        });
        
        DataStream<String> displayStream = pageStream.getSideOutput(displayTag);
        DataStream<String> startStream = pageStream.getSideOutput(startTag);
        DataStream<String> actionStream = pageStream.getSideOutput(actionTag);
        DataStream<String> errStream = pageStream.getSideOutput(errTag);
        
        HashMap<String, DataStream<String>> streams = new HashMap<>();
        streams.put("start", startStream);
        streams.put("display", displayStream);
        streams.put("err", errStream);
        streams.put("action", actionStream);
        streams.put("page", pageStream);
        
        return streams;
    }
    
    private SingleOutputStreamOperator<JSONObject> validateOldOrNew(SingleOutputStreamOperator<String> stream) {
        /*
            如果 is_new 标记为1, 有可能有误, 需要纠正. 如果是0则不需要纠正
            flink要判断每个mid是否为老访客, 需要为每个mid维护一个状态
            
            
            is_new == 1
                stat == null
                    状态中没有值, 证明确实是新用户, 给状态赋值: 今天的日期
                    
                state != null
                     状态中有值, 并且不是今天, 证明用户今天应该清除过缓存或者重装过APP导致 is_new出错,
                     给状态赋值
                     is_new 设为 0
                     
                    
               
                     
            is_new == 0
                state == null
                    状态中没值,  把状态的值设置为昨天, 可以用来纠正明天或者以后的is_new
                    
                state != null
                    ok, none do
            
         */
        
        
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {
                
                private ValueState<String> firstDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstDateState", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<JSONObject> collector) throws Exception {
                    Long ts = obj.getLong("ts");
                    String today = DateFormatUtil.toDate(ts);
                    
                    JSONObject common = obj.getJSONObject("common");
                    String isNew = common.getString("is_new");
                    String firstDate = firstDateState.value();
                    if ("1".equals(isNew)) { // 是用户
                        if (firstDate == null) { // 确实是新用户
                            firstDateState.update(today);
                        } else {
                            if (!today.equals(firstDate)) {
                                common.put("is_new", "1");
                            }
                        }
                    } else if ("0".equals(isNew)) {
                        if (firstDate == null) {
                            firstDateState.update(DateFormatUtil.toDate(ts - 24 * 60 * 60 * 1000));
                        }
                    }
                    collector.collect(obj);
                }
            });
        
    }
    
    private SingleOutputStreamOperator<String> etl(DataStreamSource<String> stream) {
        return stream.filter(json -> {
            try {
                JSON.parseObject(json); // 解析失败, 证明json格式有误, 清洗掉这些数据
                return true;
            } catch (Exception e) {
                // Key根据需求写入专门的topic
                System.out.println("数据格式有误:" + json);
                return false;
            }
        });
    }
}
